//
//  iToast.m
//  iToastDemo
//
//  Created by amao on 12/12/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "iToast.h"
#import <QuartzCore/QuartzCore.h>

const CGFloat kToastTextPadding     = 15;
const CGFloat kToastButtonPaddding  = 20;
const CGFloat kToastLabelWidth      = 280;
const CGFloat kToastLabelHeight     = 60;
const CGFloat kToastMargin          = 45;
const CGFloat kToastXOffset         = 95;
@interface iToast()
{
    int         _duration;
    UILabel* label;
    NSTimer *_timerCountDown;
}
@end
@implementation iToast
@synthesize tag;
@synthesize toastPosition;
@synthesize toastDuration;
@synthesize toastText;
@synthesize countDown;

- (id)init
{
    if (self = [super init])
    {
        toastPosition = kToastPositionCenter;
        toastDuration = kToastDurationNormal;
        _duration=(CGFloat)kToastDurationNormal;
    }
    return self;
}

- (id)initWithText:(NSString *)text
{
    if (self = [super init])
    {
        toastPosition = kToastPositionCenter;
        toastDuration = kToastDurationNormal;
        self.toastText= text;
    }
    return self;
}
-(void)setToastDuration:(ToastDuration) duration{
    toastDuration=duration;
    _duration=(int)duration;
}


+ (iToast *)makeToast:(NSString *)text
{
    iToast *toast = [[iToast alloc]initWithText:text];
    return  toast   ;
}

- (void)show
{
    UIFont *font   = [UIFont systemFontOfSize:16];
    CGSize textSize= [toastText sizeWithFont:font constrainedToSize:CGSizeMake(kToastLabelWidth, kToastLabelHeight)];
    
    label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, textSize.width + 2 * kToastTextPadding,
                                                              textSize.height + 2 * kToastTextPadding)];
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor whiteColor];
	label.font = font;
    
    if(countDown){
      label.text = [NSString stringWithFormat:@"%@ [%d]",toastText,_duration];
    }else{
        label.text = toastText;
    }
    
	label.numberOfLines = 0;
	label.shadowColor = [UIColor darkGrayColor];
	label.shadowOffset = CGSizeMake(1, 1);
    label.textAlignment = NSTextAlignmentCenter;

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
	button.bounds = CGRectMake(0, 0, textSize.width + 2 * kToastButtonPaddding, textSize.height + 2 * kToastButtonPaddding);
	label.center = CGPointMake(button.bounds.size.width / 2, button.bounds.size.height / 2);
	[button addSubview:label];
    
	
	button.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
	button.layer.cornerRadius = 5;
	
	UIWindow *window = [[[UIApplication sharedApplication] windows] objectAtIndex:0];
    CGPoint point = window.center;
    CGPoint center = window.center;
    CGFloat dx = 0;
    
    if (toastPosition == kToastPositionTop) 
    {
        point = CGPointMake(point.x, kToastMargin + button.bounds.size.height);
        dx    = center.x - kToastXOffset;
    }
    else if(toastPosition == kToastPositionBottom)
    {
        point = CGPointMake(point.x, window.bounds.size.height - kToastMargin - button.bounds.size.height);
        dx    = kToastXOffset - center.x ;

    }
    button.center = point;
    
    UIInterfaceOrientation currentOrient= [UIApplication
                                           sharedApplication].statusBarOrientation;
    
    if(currentOrient == UIDeviceOrientationLandscapeRight)
    {
        CGAffineTransform rotateTransform   = CGAffineTransformMakeRotation((M_PI/2) * -1);
        CGAffineTransform translateTransform= CGAffineTransformMakeTranslation(-dx,center.y - point.y);
        CGAffineTransform t = CGAffineTransformConcat(rotateTransform,translateTransform);
        button.transform = CGAffineTransformConcat(button.transform, t);
    }
    else if(currentOrient == UIDeviceOrientationLandscapeLeft)
    {
        CGAffineTransform rotateTransform   = CGAffineTransformMakeRotation((M_PI/2));
        CGAffineTransform translateTransform= CGAffineTransformMakeTranslation(dx,center.y - point.y);
        CGAffineTransform t = CGAffineTransformConcat(rotateTransform,translateTransform);
        button.transform = CGAffineTransformConcat(button.transform, t);
    }
    else if(currentOrient == UIDeviceOrientationPortraitUpsideDown)
    {
        button.transform = CGAffineTransformRotate(button.transform, M_PI);
    }

    [window addSubview:button];
    view = button;
    
       
      _timerCountDown=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onHideToast:) userInfo:nil repeats:YES];
    
    /*  _timerCountDown = [NSTimer timerWithTimeInterval:(CGFloat)seconds
                                              target:self selector:@selector(onHideToast:) 
                                            userInfo:nil repeats:timerRepeats];
     */
	//[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    [_timerCountDown setFireDate:[NSDate date]];
    
    [button addTarget:self action:@selector(hideToast:) forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)hideToast:(id)sender
{
    
    [self doHideToast];
}

- (void)onHideToast:(NSTimer *)timer
{
    
  /*if(!countDown){
       [self doHideToast];
      if(self.toastDelegate !=nil){
          if ([self.toastDelegate respondsToSelector:@selector(toastTimeOver:)]) {
              [self.toastDelegate toastTimeOver:self.tag];
          }
          
      }
      [timer invalidate];
      
  }else{*/
    _duration=_duration -1;
    if(_duration==0){
      [self doHideToast];
        if(self.toastDelegate !=nil){
            if ([self.toastDelegate respondsToSelector:@selector(toastTimeOver:)]) {
                [self.toastDelegate toastTimeOver:self.tag];
            }
            //[self.toastDelegate toastTimeOver:self.tag];
        }
        // [timer invalidate];
    }
  
     if(countDown){
        label.text=[NSString stringWithFormat:@"%@ [%d]",toastText,_duration];
     }    
   
}

- (void)doHideToast
{
    [_timerCountDown setFireDate:[NSDate distantFuture]];
    [UIView beginAnimations:nil context:nil];
	view.alpha = 0;
	[UIView commitAnimations];
	
     [view removeFromSuperview];
    /*
	NSTimer *timer = [NSTimer timerWithTimeInterval:500 
                                              target:self selector:@selector(onRemoveToast:)
                                            userInfo:nil repeats:NO];
	[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
*/
}

- (void)onRemoveToast:(NSTimer *)timer
{
    [view removeFromSuperview];
}

@end
